#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>


//简单的用于测试多路转接的TCP客户端
//客户端默认使用非阻塞模式,且不引入多路转接机制
int main()
{
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in server_addr;//指定服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(connect(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr)) != 0)
        std::cout << "connect error" << std::endl;
    while(true)
    {
        std::string str = "hello linux";
        std::cout << "客户端发送:" << str << std::endl;
        send(sockfd,str.c_str(),str.size(),0);
        char buffer[1024] = {0};
        int n = recv(sockfd,buffer,sizeof(buffer) - 1,0);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "对端关闭连接" << std::endl;
            break;
        }
        else
            std::cout << "recv error" << std::endl;
        sleep(2);
    }
}
